<template>
    <div>
        <el-form :model="searchForm" :rules="rules" inline>
            <el-form-item label="教师ID">
                <el-input v-model="searchForm.teacherID" @keyup.enter="search" placeholder="请输入教师ID"></el-input>
            </el-form-item>
            <el-form-item label="教师姓名">
                <el-input v-model="searchForm.teacherName" @keyup.enter="search" placeholder="请输入教师姓名"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="search">搜索</el-button>
                <el-button @click="resetForm">重置</el-button>
            </el-form-item>
        </el-form>
    </div>
    <div class="inputDiv">
        <el-form-item label="姓名">
            <el-input v-model="addForm.name" />
        </el-form-item>
        <el-form-item label="账号">
            <el-input v-model="addForm.teacherID" />
        </el-form-item>
        默认密码：123456
        <el-button class="import-el-button" @click="addPerson()">添加</el-button>
    </div>
    <el-button class="import-el-button" @click="downLoadStu()">下载名单</el-button>
    <el-table ref="multipleTableRef" :data="displayedTeacher" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column property="name" label="教师姓名" />
        <el-table-column property="teacherID" label="教师ID" show-overflow-tooltip />
        <el-table-column label="操作" width="360">
            <template #default="{ row }">
                <router-link :to="'/teacherDetail/' + row.teacherID" @click="findDetail(row)">查看详情</router-link>
                <el-button link type="primary" size="small" @click="editPerson(row)" style="margin-top: 0px;">编辑</el-button>
                <el-dialog title="编辑老师信息" v-model="dialogFormVisible" :before-close="handleClose">
                    <el-form :model="form">
                        <el-form-item label="老师姓名" :label-width="formLabelWidth">
                            <el-input v-model="form.name" autocomplete="off" />
                        </el-form-item>
                        <el-form-item label="老师ID" :label-width="formLabelWidth">
                            <el-input v-model="form.teacherID" autocomplete="off" />
                        </el-form-item>
                    </el-form>
                    <template #footer>
                        <span class="dialog-footer" @click="dialogFormVisible = false">
                            <el-button>取消</el-button>
                            <el-button type="primary" @click="saveEdit(row)">
                                確定
                            </el-button>
                        </span>
                    </template>
                </el-dialog>
                <el-button link type="primary" size="small" @click="deleteSingleTeacherFun(row)"
                    style="margin-top: 0px;">删除</el-button>
            </template>
        </el-table-column>
    </el-table>
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
        :page-sizes="[5, 10, 20, 30, 40]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
        :total="people.length">
    </el-pagination>
    <div style="margin-top: 20px">
        <el-button @click="deleteBatchTeacher">批量删除</el-button>
    </div>
</template>

<script setup>
import { ref, toRefs, reactive, computed, watch, onMounted } from 'vue';
import { ElNotification, ElDialog, ElForm, ElFormItem, ElInput, ElButton, ElPagination } from 'element-plus';
import XLSX from 'xlsx';
import { useRoute } from 'vue-router';
import { useStore } from '../store'
import { useTokenStore } from "@/stores/token.js";
import { ElTable, ElUpload } from 'element-plus'
import { addSingleTeacher, deleteSingleTeacher, editorTeacherInfo, deleteBatchTeachers, searchTeacher, classOfTeacher, classAttendOfTeacher } from '@/api/adminApi/allAdmin'
const store = useStore()
const tokenStore = useTokenStore()
const header = tokenStore.token
const fileList = ref([])
const router = useRoute();

const searchForm=ref({
    teacherID: '',
    teacherName: ''
})
const resetForm = () => {
    searchForm.value.teacherID = '';
    searchForm.value.teacherName = '';
};
const people = ref(store.teacherList);
const form = ref({
    teacherID: '',
    name: '',
    editIndex: 0
});
const addForm = ref({
    name: '',
    teacherID: ''
});
const displayedTeacher = ref([]); // 当前显示的数据
const currentPage = ref(1);
const pageSize = ref(10);

const handleSizeChange = (val) => {
    pageSize.value = val;
    currentPage.value = 1;
    displayedTeacher.value = paginateData();
};

const handleCurrentChange = (val) => {
    currentPage.value = val;
    displayedTeacher.value = paginateData();
};

const paginateData = () => {
    const startIndex = (currentPage.value - 1) * pageSize.value;
    const endIndex = startIndex + pageSize.value;
    return people.value.slice(startIndex, endIndex);
};
onMounted(() => {
    displayedTeacher.value = paginateData();
})
const multipleTableRef = ref()
const dialogFormVisible = ref(false);
const addPerson = async () => {
    const data = {
        name: addForm.value.name,
        teacherID: addForm.value.teacherID,
        password: '123456'
    };
    displayedTeacher.value.push(data)
    addForm.value = {}
    await addSingleTeacher(data)
};
//保存多选行的信息
const selectionRow = ref([])
const handleSelectionChange = (section) => {
    selectionRow.value = section
}
//批量删除
const deleteBatchTeacher = async () => {
    const data = []
    selectionRow.value.map((item, index) => {
        data.push(item.teacherID)
        people.value.map((list, idx) => {
            if (item.teacherID === list.teacherID)
                peodisplayedTeacherple.value.splice(idx, 1)
        })
    })
    await deleteBatchTeachers(data)
}
const editPerson = async (row) => {
    // 处理选中行数据
    form.value.name = row.name;
    form.value.teacherID = row.teacherID;
    dialogFormVisible.value = true;
}
//删除单个老师
const deleteSingleTeacherFun = async (row) => {
    const index = people.value.findIndex(item => item.teacherID === row.teacherID);
    displayedTeacher.value.splice(index, 1)
    await deleteSingleTeacher(row.teacherID)
};
//保存编辑内容
const saveEdit = async () => {
    const data = {
        name: form.value.name,
        password: "123456",//设为初始值
        teacherID: form.value.teacherID
    }
    await editorTeacherInfo(data)
    const index = people.value.findIndex((item) => item.teacherID === form.value.teacherID)
    people.value[index].name = form.value.name
}
const searchQuery = ref('');

const search = async () => {
    let result={
        teacherID:searchForm.value.teacherID,
        name:searchForm.value.teacherName,
        pageSize:20,
        pageNum:1
    }
    const res = await searchTeacher(result)
    displayedTeacher.value = res.data
    people.value=res.data
};

//查看详情
const findDetail = async (data) => {
    store.setDetailTeacher(data)
    //创建的课程
    const list = await classOfTeacher(data.teacherID)
    store.setCreateClass(list.data)
    //加入的课程
    const list2 = await classAttendOfTeacher(data.teacherID)
    store.setAttendClass(list2.data)
}
const handleCloseDialog = (done) => {
    form.value.teacherId = '';
    form.value.teacherName = '';
    done();
};

// 将响应式数据转换为可解构的对象
const { value: reactivePeople } = toRefs(people);
const downLoadStu = () => {
    const worksheet = XLSX.utils.json_to_sheet(people.value);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
    XLSX.writeFile(workbook, 'teachers.xlsx');
}
//批量导入
// const beforeUpload = (file) => {
//     console.log(file)
const headers = {
    token: header.token
}
console.log(headers, '  headers ')

//     return  {headers}
// }
const handleFileUpload = (event) => {
    const file = event.target.files[0];
    const reader = new FileReader();

    reader.onload = (e) => {
        const data = new Uint8Array(e.target.result);
        const workbook = XLSX.read(data, { type: 'array' });
        const worksheet = workbook.Sheets[workbook.SheetNames[0]];
        const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

        // 将数据存入ref
        people.value = jsonData.map((row, index) => {
            if (index === 0) return null; // 跳过表头行
            const [id, teacherId, teacherName] = row;
            return { id, teacherId, teacherName };
        }).filter(Boolean);
    };

    reader.readAsArrayBuffer(file);
}
watch(
    () => store.teacherList,
    () => people.value = store.teacherList,
    { deep: true }
)
</script>

<style>
.dialog-footer {
    display: flex;
    justify-content: flex-end;
}

.import_div {
    display: inline-block;
    margin-left: 28%;
}
</style>

<!-- 引入 Element Plus 组件库 -->

<script>
export default {
    components: {
        ElNotification,
        ElDialog,
        ElForm,
        ElFormItem,
        ElInput,
        ElButton,
    },
};
</script>@/api/adminApi/allAdmin